#include "StdAfx.h"
#include "FormUserEdit.h"
#include "FormUserList.h"
#include "User.h"

namespace wlog {

	void FormUserEdit::LoadUser(void)
	{
		if (this->id_user > 0)
		{
			User^ user = gcnew User(this->id_user);
			this->textUserName->Text = user->name;
			this->textPasssword->Text = user->password;

			this->textUserName->ReadOnly = true;

			this->checkBoxADM->Checked = false;
			if (!user->adm->Equals("0"))
			{
				this->checkBoxADM->Checked = true;			
			}
			this->checkBoxStatus->Checked = false;
			if (user->active->Equals("1"))
			{
				this->checkBoxStatus->Checked = true;
			}
		
		}
		
	
	}

	void FormUserEdit::SaveUser(void)
	{
		String^ name = this->textUserName->Text;
		if (name->Length < 4)
		{
			this->labelTip->Text = FormUserEdit::NAME_TIP;
			this->textUserName->Focus();
			return;		
		}

		User^ user = gcnew User(this->id_user);
		user->name = name;
		user->password = this->textPasssword->Text;
		
		user->adm = "0";
		if (this->checkBoxADM->Checked)
		{
			user->adm = "1";
		}
		
		user->active = "0";
		if (this->checkBoxStatus->Checked)
		{
			user->active = "1";
		}
		user->Save();


		if (this->id_user == 0)
		{
			int insert_id = user->GetInsertId();

			Hashtable^ item = user->GetFields();
			item["name"] = Sqlite::parseValue(user->name);
			item["adm"] = user->adm;
			item["date_login"] = "";
			item->Add("id", insert_id.ToString());

			FormUserList::INSTANCE->LoadSingle(item);
		}
		else
		{
			FormUserList::INSTANCE->UpdateUserList(user->adm, user->active);
		}
		this->Close();
	}



}